<template>
  <div class="userManagement">
    <div class="searchBox">
      <div class="itemBox">
        <div class="itemTitle">角色名称</div>
        <el-input
          class="itemInput"
          v-model="userMsg"
          placeholder="请输入角色名称"
        />
      </div>
      <div class="itemBox">
        <div class="itemTitle">创建人</div>
        <el-input
          class="itemInput"
          v-model="founder"
          placeholder="请输入创建人姓名"
        />
      </div>
      <div class="itemBox">
        <div class="itemTitle">创建时间</div>
        <el-date-picker
          v-model="creationTime"
          class="creationTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
        <img src="@/assets/images/changeTime.png" alt="" class="timeImg" />
      </div>
      <!--   操作按钮   -->
      <div class="operationBox">
        <div class="resetBox" @click="reset()">重置</div>
        <div class="queryBox" @click="getDatalist()">查询</div>
      </div>
    </div>
    <div class="content">
      <div class="addBox" @click="addUser()">新增</div>
      <div class="tableBox">
        <el-table
          :data="tableData"
          style="width: 100%"
          height="660"
          :header-cell-style="{
            background: '#F7F8FA',
            color: '#203549',
          }"
        >
          <el-table-column type="index" label="序号" align="center">
            <template slot-scope="scope">
              {{
                (pageData.currentPage - 1) * pageData.pageSize +
                scope.$index +
                1
              }}
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" align="center" />
          <el-table-column prop="remarks" label="权限说明" align="center" />
          <el-table-column prop="creatorName" label="创建人" align="center" />
          <el-table-column label="创建时间" align="center">
            <template slot-scope="scope">
              {{
                scope.row.createTime ? scope.row.createTime.slice(0, 10) : ''
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="tableOperation" v-if="scope.row.isRoot == 0">
                <div @click="handleEdit(scope.row)" class="edit">编辑</div>
                <div @click="handleDelete(scope.row)" class="delete">删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <Pagination @getData="getData" :pageData="pageData" />
    </div>

    <!--  新增/编辑角色  -->
    <el-dialog :visible.sync="dialogVisible" width="600px" class="addDialog">
      <div class="dialogContent">
        <div class="header">{{ dialogType == 0 ? '新增' : '编辑' }}角色</div>
        <div class="main">
          <div class="item">
            <div class="title"><span>*</span>角色名称</div>
            <el-input v-model="roleName" placeholder="请输入内容" />
          </div>
          <div class="item">
            <div class="title">权限说明</div>
            <el-input
              v-model="permissionSpecification"
              placeholder="请输入内容"
            />
          </div>
          <div class="item">
            <div class="title"><span>*</span>功能权限</div>
            <div class="treeBox">
              <el-checkbox v-model="checked" @change="changeChecked"
                >全选</el-checkbox
              >
              <el-tree
                ref="menuOrUserTree"
                :data="treeData"
                show-checkbox
                accordion
                node-key="id"
                :props="defaultProps"
                @check="checkPermission"
              />
            </div>
          </div>
        </div>
        <div class="hr"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm()">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import debounce from '@/utils/js/debounce';
import Pagination from '@/components/Pagination';
import { timeMode } from '@/utils/js/util';
export default {
  name: 'UserManagement',
  data() {
    return {
      // 新增角色弹窗
      dialogVisible: false,

      // 0--新增角色  1--编辑角色
      dialogType: 0,

      // 角色名称
      userMsg: '',

      // 创建人
      founder: '',

      //  创建时间
      creationTime: '',

      tableData: [],

      // 传给分页的数据
      pageData: {
        total: 10,
        pageSize: 10,
        currentPage: 1,
      },

      //  角色名称
      roleName: '',
      //  权限说明
      permissionSpecification: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      checked: false,
      treeIdArr: [],
      checkedKeysList: [],
      roleId: '',
      halfCheckedKeys: [],

      allTreeSonId: [],
    };
  },
  mounted() {
    this.getDatalist();
    this.getTree();
  },
  methods: {
    //  重置
    reset() {
      this.userMsg = '';
      this.founder = '';
      this.creationTime = '';
      this.pageData = {
        total: 10,
        pageSize: 10,
        currentPage: 1,
      };
      this.getDatalist();
    },

    // 获取权限树
    getTree() {
      this.$http
        .getAllSPermissionsSystem()
        .then(res => {
          let { data, code } = res;
          if (code == '0000000000' && data.length) {
            let arr = [],
              sonArr = [];
            data[0].children.forEach(item => {
              item.newArr = [];
              item.children.forEach(ite => {
                item.newArr.push({ id: ite.permissionId, label: ite.name });
                sonArr.push(ite.permissionId);
              });
              arr.push({
                id: item.permissionId,
                label: item.name,
                children: item.newArr,
              });
            });
            this.treeData = arr;
            this.allTreeSonId = sonArr;
          }
        })
        .catch(() => {});
    },

    // 获取列表数据
    getDatalist() {
      let startTime = '',
        endTime = '';
      if (this.creationTime) {
        startTime =
          timeMode(this.creationTime[0]).datestr + ' 00:' + '00:' + '00';
        endTime =
          timeMode(this.creationTime[1]).datestr + ' 23:' + '59:' + '59';
      }
      let params = {
        pageSize: this.pageData.pageSize,
        page: this.pageData.currentPage,
        roleName: this.userMsg,
        creatorName: this.founder,
        startTime,
        endTime,
      };
      this.$http
        .findSystemRoleListSystem(params)
        .then(res => {
          let { data } = res;
          this.tableData = data.records;

          this.pageData = {
            total: data.total,
            pageSize: this.pageData.pageSize,
            currentPage: this.pageData.currentPage,
          };
        })
        .catch(() => {});
    },

    // 新增
    addUser() {
      this.dialogType = 0;
      this.dialogVisible = true;
      this.clearData();
    },

    // 清除弹窗数据
    clearData() {
      this.roleName = '';
      this.permissionSpecification = '';
      this.treeIdArr = [];
      this.checked = false;
      this.checkedKeysList = [];
      this.$nextTick(() => {
        this.$refs.menuOrUserTree.setCheckedKeys(this.treeIdArr);
      });
    },

    // 提示信息
    elart(message, type) {
      this.$message({
        message,
        type: type || 'success',
      });
    },

    // 用户新增/编辑确定
    submitForm: debounce(function () {
      let permissionIds = [1, ...this.$refs.menuOrUserTree.getCheckedKeys()];
      if (!this.roleName) {
        this.elart('请输入角色名称！', 'error');
      } else if (
        !this.checkedKeysList.length &&
        !this.checked &&
        this.dialogType == 0
      ) {
        this.elart('请选择功能权限！', 'error');
      } else {
        if (this.halfCheckedKeys.length) {
          permissionIds = [
            1,
            ...this.$refs.menuOrUserTree.getCheckedKeys(),
            ...this.halfCheckedKeys,
          ];
        }

        let params = {
          roleName: this.roleName,
          creatorId: sessionStorage.getItem('accountId'),
          remarks: this.permissionSpecification,
          permissionIds,
        };
        if (this.dialogType == 0) {
          this.$http
            .addSystemRoleSystem(params)
            .then(res => {
              if (res.code == '0000000000') {
                this.elart('添加成功！');
                this.dialogVisible = false;
                this.clearData();
                this.$refs.menuOrUserTree.setCheckedKeys(this.treeIdArr);
                this.getDatalist();
              }
            })
            .catch(() => {});
        } else {
          params.roleId = this.roleId;
          this.$http
            .editSystemRoleSystem(params)
            .then(res => {
              if (res.code == '0000000000') {
                this.elart('修改成功！');
                this.dialogVisible = false;
                this.clearData();
                this.$refs.menuOrUserTree.setCheckedKeys(this.treeIdArr);
                this.getDatalist();
              }
            })
            .catch(() => {});
        }
      }
    }, 500),

    // 用户新增取消
    resetForm() {
      this.dialogVisible = false;
    },

    //  分页数据改变
    getData(val) {
      this.pageData = val;
      this.getDatalist();
    },

    // 编辑
    handleEdit(val) {
      this.dialogType = 1;
      this.dialogVisible = true;
      this.treeIdArr = [];
      this.roleName = val.roleName;
      this.permissionSpecification = val.remarks;
      this.roleId = val.roleId;
      this.getTreeId(this.treeData);
      let arr = val.permissionIds.split(',');
      if (val.permissionIds == this.allTreeSonId.join(',')) {
        this.checked = true;
      } else {
        this.checked = false;
      }
      this.$nextTick(() => {
        this.$refs.menuOrUserTree.setCheckedKeys(arr);
      });
    },

    //  删除
    handleDelete(val) {
      this.$confirm('此操作将删除该账号, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let params = {
            roleId: val.roleId,
          };
          this.$http
            .deleteSystemRoleSystem(params)
            .then(res => {
              if (res.code == '0000000000') {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                });
                this.getDatalist();
              }
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    //  功能权限选择
    checkPermission(checkedNodes, checkedKeys) {
      this.checkedKeysList = checkedKeys.checkedKeys;
      // 保存半全选的一级菜单id
      if (checkedKeys.halfCheckedKeys.length) {
        this.halfCheckedKeys = checkedKeys.halfCheckedKeys;
      }
      // 控制全选与反全选
      if (!this.checked && !this.treeIdArr.length) {
        this.getTreeId(this.treeData);
      }
      if (checkedKeys.checkedKeys.length == this.treeIdArr.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },

    //  功能权限全选
    changeChecked() {
      if (this.checked) {
        this.getTreeId(this.treeData);
      } else {
        this.treeIdArr = [];
      }
      this.$refs.menuOrUserTree.setCheckedKeys(this.treeIdArr);
    },

    // 获取多选权限id
    getTreeId(arr) {
      arr.forEach(item => {
        this.treeIdArr.push(item.id);
        if (item.children) {
          this.getTreeId(item.children);
        }
      });
    },
  },
  components: {
    Pagination,
  },
};
</script>

<style scoped lang="less">
.userManagement {
  .searchBox {
    height: 64px;
    background: #fff;
    padding: 16px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .itemBox {
      display: flex;
      align-items: center;
      margin-right: 32px;
      position: relative;

      .itemTitle {
        font-size: 14px;
        font-weight: 400;
        color: #111111;
        white-space: nowrap;
        text-align: right;
      }
      /deep/ .itemInput {
        margin-left: 8px;

        .el-input__inner {
          width: 240px;
          height: 32px;
        }
        .el-input__icon {
          line-height: 32px;
        }
      }

      /deep/ .creationTime {
        width: 310px;
        height: 32px;
        margin-left: 8px;
        .el-icon-date {
          display: none;
        }
        .el-range-input {
          text-align: left;
        }
        .el-range-separator {
          width: 10%;
          margin-top: -8px;
        }
      }
      .timeImg {
        width: 18px;
        position: absolute;
        right: 8px;
      }
    }
    .operationBox {
      display: flex;
      .resetBox {
        width: 76px;
        height: 32px;
        border-radius: 2px;
        border: 1px solid #dcdfe6;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        font-weight: 400;
        color: #606266;
        cursor: pointer;
        box-sizing: border-box;
      }
      .queryBox {
        width: 76px;
        height: 32px;
        background: #0a73e4;
        border-radius: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
        margin-left: 8px;
      }
    }
  }
  .content {
    background: #fff;
    padding: 16px;
    box-sizing: border-box;
    margin-top: 16px;
    height: 800px;
    position: relative;
    .addBox {
      width: 76px;
      height: 32px;
      background: #0a73e4;
      border-radius: 2px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      font-size: 14px;
      font-weight: 400;
      color: #ffffff;
      margin-bottom: 16px;
    }
    .tableBox {
      .tableOperation {
        display: flex;
        .edit {
          font-size: 14px;
          font-weight: 400;
          color: #0a73e4;
          cursor: pointer;
        }
        .delete {
          font-size: 14px;
          font-weight: 400;
          color: #ff595a;
          margin-left: 16px;
          cursor: pointer;
        }
      }
    }
  }
  /deep/ .addDialog {
    .el-dialog__header,
    .el-dialog__body {
      padding: 0;
    }
    .dialogContent {
      .header {
        height: 54px;
        border-bottom: 1px solid #e9e8eb;
        font-size: 16px;
        font-weight: 500;
        color: #101b25;
        line-height: 54px;
        padding-left: 16px;
        box-sizing: border-box;
      }
      .main {
        padding: 24px 98px;
        box-sizing: border-box;
        .item {
          display: flex;
          margin-bottom: 12px;
          .title {
            font-size: 14px;
            color: #101b25;
            width: 120px;
            margin-right: 8px;
            text-align: right;
            margin-top: 10px;
            span {
              color: #e21b1b;
            }
          }
          .el-input__inner {
            width: 330px;
            height: 32px;
          }
          .treeBox {
            width: 580px;
            height: 310px;
            border-radius: 2px;
            border: 1px solid #dcdee0;
            padding: 16px;
            box-sizing: border-box;
            overflow-y: scroll;
            .el-tree {
              margin-top: 12px;
            }
          }
          .treeBox::-webkit-scrollbar {
            width: 0;
            height: 0; /**/
          }
          .treeBox::-webkit-scrollbar-track {
            background: rgb(239, 239, 239);
            border-radius: 2px;
          }
          .treeBox::-webkit-scrollbar-thumb {
            background: #bfbfbf;
            border-radius: 0;
          }
        }
      }
      .hr {
        height: 2px;
        background: #e9e8eb;
      }
    }
  }
}
</style>
